from server.app.cloud_ide.schema.ide_image.request.ide_image_create_request import IdeImageCreateRequest
from server.app.cloud_ide.schema.ide_image.request.ide_image_update_request import IdeImageUpdateRequest
from server.app.cloud_ide.schema.ide_registry.request.ide_registry_create_request import IdeRegistryCreateRequest
from server.app.cloud_ide.schema.ide_registry.request.ide_registry_update_request import IdeRegistryUpdateRequest
from server.app.cloud_ide.service.ide_image_service import IdeImageService
from server.app.cloud_ide.service.ide_registry_service import IdeRegistryService
from behave import *

from server.framework.core.database import SessionLocal
from server.framework.core.logger import logger

ide_image_service = IdeImageService()
ide_registry_service = IdeRegistryService()
db = SessionLocal()


@step('查看镜像详情列表')
def 查看镜像详情列表(context):
    ide_image_service.get_ide_image_list(db=db, page_size=10, current_page=1, name=None)


@step('在镜像源[{registry_name}]下新增镜像,信息如下')
def 新增镜像源_下新增镜像信息如下(context, registry_name):
    target_registry = ide_registry_service.find_ide_registry_by_name(db, registry_name)

    for row in context.table:
        rs = ide_image_service.create_ide_image(db=db, data=IdeImageCreateRequest(
            name=row['name'],
            version=row['version'],
            ide_registry_id=str(target_registry.id),
            git_url=row['git_url'],
            note=row['note'],
            status=int(row['status']),
            ide_type=int(row['ide_type']),
        ))
        assert rs


@step('查看镜像[{name}]的详情信息')
def 查看镜像_的详情信息(context, name):
    target = ide_registry_service.find_ide_registry_by_name(db=db, name=name)
    rs = ide_registry_service.get_ide_registry_by_id(db, target.id)
    assert rs is not None


@step('删除以下镜像')
def 删除以下镜像(context):
    names = [x['name'] for x in context.table]
    for name in names:
        target = ide_registry_service.find_ide_registry_by_name(db=db, name=name)
        if target is not None:
            ide_registry_service.delete_ide_registry(db=db, ids=[str(target.id)])


@step('编辑镜像源[{registry_name}]下的镜像[{image_name}],信息如下')
def 编辑镜像源_下的镜像_信息如下(context, registry_name, image_name):
    target = ide_registry_service.find_ide_registry_by_name(db=db, name=registry_name)
    for row in context.table:
        rs = ide_image_service.update_ide_image(db=db, data=IdeImageUpdateRequest(
            name=row['name'],
            version=row['version'],
            ide_registry_id=str(target.id),
            git_url=row['git_url'],
            note=row['note'],
            status=int(row['status']),
            ide_type=int(row['ide_type']),
            id=str(target.id)
        ))
        assert rs
